package com.heima.intercept;

import com.heima.utils.CurrentHolder;
import com.heima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 赵超
 */
@Component
@Slf4j
public class AdminTokenIntercept implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            //TODO 后期封装成常量
            response.setStatus(401);
            return false;
        }
        try {
            Claims claims = JwtUtils.parseJwt(token);
            //TODO 后期封装成常量
            Long userId = Long.valueOf(claims.get("userId").toString());
            log.info("当前用户userId:{}", userId);
            CurrentHolder.setCurrentId(userId);
        } catch (Exception e) {
            //TODO 后期封装成常量
            response.setStatus(401);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        CurrentHolder.removeCurrentId();
    }
}
